package fsu.cs.cis5930;

import android.app.Activity;

import java.io.IOException;
import java.lang.Object;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class Connection  {
	/**
	 * ConnectionType allows us to know whether we are using BlueTooth or TCP to communicate with
	 * the other players. This affects how messages are sent between the phones.
	 */
	enum Type
	{	SINGLE_PLAYER,
		BLUETOOTH,
		TCP	}


	/**
	 * Enumeration which holds all possible messages that may be sent to the server or other phone.
	 */
	enum Messages
	{
		/** sent when connection is established, runs gameStart() function */
		START_GAME,
		/** sent when a bomb explodes, runs gameEnd() function */
		END_GAME,
		/** sent when a bomb is clicked */
		SEND_BOMB		
		}
	
	
    /** Called when the activity is first created. */
	private Handler mHandler, mChildHandler;
  
	/**
	 *  Constructor called by game engine. Sets the appropriate threads to run.
	 */
    public Connection( Type type) {

    	switch (type)
    	{
    	case SINGLE_PLAYER:
    		return;
    	case BLUETOOTH:
    		// TODO
    		break;
    	case TCP:
    		Thread s = new Thread(new TCP());
    		break;
    	}

    }
    
    public void sendMessage(Messages type, Object msg)
    {
    	/** If handler has not been set yet, wait and try again. Then fail */
    	if ( mChildHandler == null)
    	{
    		try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    		if ( mChildHandler == null)
    			throw new RuntimeException("Problems setting the connection up.");
    	}
    		
    	mChildHandler.sendMessage(Message.obtain(mChildHandler, type.ordinal(), msg));
    	
    }
    

    
    /////////////////////////////
    /////Received messages come in to here with all the data inside msg.obj
    /////can make a switch statement to do what u need to with the data received
    ////////////////////////////
    
    private Handler messageHandler = new Handler(){
    	public void handleMessage(Message msg){
    		Log.d("MSGH: " , msg.obj.toString());
    	}
    };
    

    
    public class TCP implements Runnable {

        Socket ourConnection = null;
    	String server = "68.63.37.207";
    	final int port = 5000;
    	OutputStream os = null;
    	BufferedReader in = null;
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		Looper.prepare();
    		
    		mChildHandler = new Handler(){
    			public void handleMessage(Message msg){
    				Log.d("Child: ", "GOT SOMETHING");
    				 sendToServer(4, 10);
    				
    			}
    			
    		};
    		

    		
 
            try {
            	
            	InetAddress servadd = InetAddress.getByName(server);
            	Log.d("TCP", "Connecting...");
            	ourConnection = new Socket();
            	ourConnection  = new Socket(servadd, port);
            	os = ourConnection.getOutputStream();
            	in = new BufferedReader(new InputStreamReader(ourConnection.getInputStream()));

            }
            catch(UnknownHostException e){
            	e.printStackTrace();
            }
            catch(IOException e){
            	e.printStackTrace();
            	
            }  
            
            catch(SecurityException e){
            	e.printStackTrace();
            }
            
            new Thread(new Runnable(){   //this reads from the server
            	public void run(){
  //          		char[] buff = new char[24];
            
     //       		byte[] arr;
            		
            		
            		boolean go = true;
            		while(go){
            		try {
            			String temp;
            		//	Log.d("RECV:", "Started REcv");
    				    //in.read(buff, 0, 24);
    				    temp = in.readLine();
    				    String[] nums = temp.split("\\s");
    				    int count = 0;
    				    int[] numbs = new int[2];
    				    for(String s: nums){
    				    	int i = -1;
    				    	try{ i = Integer.parseInt(s);}
    				    	catch(Exception ex){i = -1;}
    				    	if(i>0){
    				    		numbs[count] = i;
    				    		count++;
    				    	}
    				    }
    				    
    				    
    				    String tmsg = "";
    				    for(int gt=0; gt<count; gt++){
    				    	tmsg = tmsg + numbs[gt] + " " ;
    				    	
    				    }
    				    messageHandler.sendMessage(Message.obtain(messageHandler, 1, tmsg));
    				    
    				    
    					
    					
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
            		}
            		
            		
            	}
            }).start();
            

        
            Looper.loop();

    		
    	
    	}
    	
    
    	
    	public void sendToServer(int type, int extraData){
    	 		
//    		byte[] arr = new byte[12];
    		ByteBuffer b = ByteBuffer.allocate(12);
    		b = b.order(ByteOrder.LITTLE_ENDIAN);
    		b = b.putInt(12);
    		b = b.putInt(type);
    		b = b.putInt(extraData);
    	
    		byte[] res = b.array();

    		try{
    			os.write(res);	
    		}
    		catch(Exception e){
    			
    		}
    		
    		
    	}
    	
    }
    
}